'''
Author: wuxiangyi
Date: 2022-05-27 15:30:14
LastEditors: wuxiangyi
LastEditTime: 2022-05-31 16:26:27
FilePath: /毕业论文自动化系统/MyFrameMain.py
Description: 

'''
from glob import glob
import math
import os  # 文件操作相关
import sys
from tokenize import Number
from urllib import request  # 额外接受参数操作
from utils import win1
from utils import win2
from textrank4zh import TextRank4Keyword, TextRank4Sentence  # 从文本从提取关键词、句相关
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QFileDialog, QTableWidgetItem, QHeaderView  # 窗体工具相关
from PyQt5.QtCore import Qt
from utils import ExcelParse
from utils import Word

# 当前窗口
ex = None
# # 当前小时
# currentHour = 8
# # 当前分钟
# currentMin = 0
# 下午答辩第一位序号
afterFirstNo = 57

class showWin1(QWidget):
    # 构造函数
    def __init__(self):
        '''
        初始化的UI
        '''
        super().__init__()
        self.temporary = 0
        self.ui = win1.Ui_Form()
        self.ui.setupUi(self)
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.show()
        self.message = []

    # 选择Excel
    def openExcel(self):
        fileName1, filetype = QFileDialog.getOpenFileName(self, "选取文件", "./","Excel Files (*.xls)")
        if fileName1 != '':
             # 清空缓存
            self.message = []
            # 清空表格
            self.ui.tableWidget.setRowCount(0)
            self.ui.tableWidget.clearContents()
            data = ExcelParse.main(fileName1, '选题一览表' , 7)
            for info in data:
                record = {}
                record['number'] = info[0]
                record['title'] = info[1]
                record['class'] = '计算机科学与技术' + info[2].replace('计科',"")
                record['studentNumber'] = info[3]
                record['studentName'] = info[4]
                record['instructorTeacher'] = info[5]
                record['reviewTeacher'] = info[6]
                # 指导老师分数
                instructorTeacherScore = 0
                if math.isnan(info[7]) == False:
                    instructorTeacherScore = int(info[7])
                record['instructorTeacherScore'] = instructorTeacherScore
                # 评阅老师分数
                reviewTeacherScore = 0
                if math.isnan(info[8]) == False:
                    reviewTeacherScore = int(info[8])
                record['reviewTeacherScore'] = reviewTeacherScore
                # 开题答辩分数
                openingDefenseScore = 0
                if math.isnan(info[9]) == False:
                    openingDefenseScore = int(info[9])
                record['openingDefenseScore'] = openingDefenseScore
                # 中期检查分数
                interimExaminationScore = 0
                if math.isnan(info[10]) == False:
                    interimExaminationScore = int(info[10])
                record['interimExaminationScore'] = interimExaminationScore
                # 答辩现场分数
                defenseSiteScore1 = 0
                if math.isnan(info[11]) == False:
                    defenseSiteScore1 = int(info[11])
                record['defenseSiteScore1'] = defenseSiteScore1
                defenseSiteScore2 = 0
                if math.isnan(info[12]) == False:
                    defenseSiteScore2 = int(info[12])
                record['defenseSiteScore2'] = defenseSiteScore2
                defenseSiteScore3 = 0
                if math.isnan(info[13]) == False:
                    defenseSiteScore3 = int(info[13])
                record['defenseSiteScore3'] = defenseSiteScore3
                defenseSiteScore4 = 0
                if math.isnan(info[14]) == False:
                    defenseSiteScore4 = int(info[14])
                record['defenseSiteScore4'] = defenseSiteScore4
                # 答辩分数
                defenseScore = (defenseSiteScore1 + defenseSiteScore2 + defenseSiteScore3 + defenseSiteScore4) / 4
                # record['defenseScore'] = round(defenseScore , 2)
                record['defenseScore'] = math.ceil(defenseScore)
                # 论文分数
                thesisScore = instructorTeacherScore * 0.2 + reviewTeacherScore * 0.1 + openingDefenseScore * 0.1 + interimExaminationScore * 0.1 + defenseScore * 0.5
                # record['thesisScore'] = round(thesisScore , 2)
                record['thesisScore'] = math.ceil(thesisScore)
                self.message.append(record)
            # 将解析的excel结果展示在table组件中
            index = 0
            for obj in self.message:
                self.ui.tableWidget.insertRow(index)
                self.ui.tableWidget.setItem(index , 0 , QTableWidgetItem(str(obj['number'])))
                self.ui.tableWidget.setItem(index , 1 , QTableWidgetItem(str(obj['title'])))
                self.ui.tableWidget.setItem(index , 2 , QTableWidgetItem(str(obj['class'])))
                self.ui.tableWidget.setItem(index , 3 , QTableWidgetItem(str(obj['studentNumber'])))
                self.ui.tableWidget.setItem(index , 4 , QTableWidgetItem(str(obj['studentName'])))
                self.ui.tableWidget.setItem(index , 5 , QTableWidgetItem(str(obj['instructorTeacher'])))
                self.ui.tableWidget.setItem(index , 6 , QTableWidgetItem(str(obj['reviewTeacher'])))
                self.ui.tableWidget.setItem(index , 7 , QTableWidgetItem(str(obj['instructorTeacherScore'])))
                self.ui.tableWidget.setItem(index , 8 , QTableWidgetItem(str(obj['reviewTeacherScore'])))
                self.ui.tableWidget.setItem(index , 9 , QTableWidgetItem(str(obj['openingDefenseScore'])))
                self.ui.tableWidget.setItem(index , 10 , QTableWidgetItem(str(obj['interimExaminationScore'])))
                self.ui.tableWidget.setItem(index , 11 , QTableWidgetItem(str(obj['defenseSiteScore1'])))
                self.ui.tableWidget.setItem(index , 12 , QTableWidgetItem(str(obj['defenseSiteScore2'])))
                self.ui.tableWidget.setItem(index , 13 , QTableWidgetItem(str(obj['defenseSiteScore3'])))
                self.ui.tableWidget.setItem(index , 14 , QTableWidgetItem(str(obj['defenseSiteScore4'])))
                self.ui.tableWidget.setItem(index , 15 , QTableWidgetItem(str(obj['defenseScore'])))
                self.ui.tableWidget.setItem(index , 16 , QTableWidgetItem(str(obj['thesisScore'])))
                index = index + 1


    def next(self):
        if len(self.message) == 0:
            QMessageBox.critical(None, "未选择Excel文件", "请先选择Excel文件")
        else: 
            self.message = []
            for i in range(self.ui.tableWidget.rowCount()):
                record = {}
                for j in range(self.ui.tableWidget.columnCount()):
                    if j == 0:
                        record['number'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 1:
                        record['title'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 2:
                        record['class'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 3:
                        record['studentNumber'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 4:
                        record['studentName'] = self.ui.tableWidget.item(i, j).text()
                    elif j == 5:
                        record['instructorTeacher'] = self.ui.tableWidget.item(i , j).text()
                    elif j == 6:
                        record['reviewTeacher'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 7:
                        record['instructorTeacherScore'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 8:
                        record['reviewTeacherScore'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 9:
                        record['openingDefenseScore'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 10:
                        record['interimExaminationScore'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 11:
                        record['defenseSiteScore1'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 12:
                        record['defenseSiteScore2'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 13:
                        record['defenseSiteScore3'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 14:
                        record['defenseSiteScore4'] = self.ui.tableWidget.item(i,j).text()
                    elif j == 15:
                        record['defenseScore'] = self.ui.tableWidget.item(i,j).text()
                    else:
                        record['thesisScore'] = self.ui.tableWidget.item(i,j).text()
                self.message.append(record)
            runWin2(self.message)

class showWin2(QWidget):
    # 数据插入文本栏
    def insertData(self):
        self.ui.LineEdit_1.setText(str(self.message[self.index]['number']))
        self.ui.LineEdit_2.setText(str(self.message[self.index]['title']))
        self.ui.LineEdit_3.setText(str(self.message[self.index]['class']))
        self.ui.LineEdit_4.setText(str(self.message[self.index]['studentNumber']))
        self.ui.LineEdit_5.setText(str(self.message[self.index]['studentName']))
        self.ui.LineEdit_6.setText(str(self.message[self.index]['instructorTeacher']))
        self.ui.LineEdit_7.setText(str(self.message[self.index]['reviewTeacher']))
        self.ui.LineEdit_8.setText(str(self.message[self.index]['instructorTeacherScore']))
        self.ui.LineEdit_9.setText(str(self.message[self.index]['reviewTeacherScore']))
        self.ui.LineEdit_10.setText(str(self.message[self.index]['openingDefenseScore']))
        self.ui.LineEdit_11.setText(str(self.message[self.index]['interimExaminationScore']))
        self.ui.LineEdit_12.setText(str(self.message[self.index]['defenseSiteScore1']))
        self.ui.LineEdit_13.setText(str(self.message[self.index]['defenseSiteScore2']))
        self.ui.LineEdit_14.setText(str(self.message[self.index]['defenseSiteScore3']))
        self.ui.LineEdit_15.setText(str(self.message[self.index]['defenseSiteScore4']))
        self.ui.LineEdit_16.setText(str(self.message[self.index]['defenseScore']))
        self.ui.LineEdit_17.setText(str(self.message[self.index]['thesisScore']))
        record = {
            'title': self.message[self.index]['title'],
            'studentName': self.message[self.index]['studentName'],
            'number': self.message[self.index]['number']
        }
        Word.setInitValue(self , record)

    # 构造函数
    def __init__(self , message):
        '''
        初始化的UI
        '''
        super().__init__()
        self.temporary = 0
        self.ui = win2.Ui_Form()
        self.ui.setupUi(self)
        # self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.show()
        self.message = message
        self.index = 0
        self.insertData()

    # 上一个
    def toPreObject(self):
        if self.index == 0:
            QMessageBox.critical(None, "当前是第一页", "当前是第一页")
        else:
            self.index = self.index - 1
            self.insertData()

    # 下一个
    def toAfaterObject(self):
        if self.index == len(self.message) - 1:
            QMessageBox.critical(None, "当前是最后一页", "当前是最后一页")
        else:
            self.index = self.index + 1
            self.insertData()

    # 生成文档
    def generateFile(self):
        studentName = self.message[self.index]['studentName']
        className = self.message[self.index]['class']
        number = self.message[self.index]['number']
        defenseScore = self.message[self.index]['defenseScore']
        thesisScore = self.message[self.index]['thesisScore']
        title = self.message[self.index]['title']
        request1 = self.ui.request1.text()
        # ask1 = self.ui.ask1.text()
        ask1 = self.ui.comboBox.currentText()
        request2 = self.ui.request2.text()
        # ask2 = self.ui.ask2.text()
        ask2 = self.ui.comboBox_2.currentText()
        request3 = self.ui.request3.text()
        # ask3 = self.ui.ask3.text()
        ask3 = self.ui.comboBox_3.currentText()
        record = {
            'studentName': studentName,
            'title': title,
            'class': className,
            'number': number,
            'request1': request1,
            'request2': request2,
            'request3': request3,
            'ask1': ask1,
            'ask2': ask2,
            'ask3': ask3,
            'defenseScore': defenseScore,
            'thesisScore': thesisScore,
        }
        path = Word.main(record)
        self.ui.logText.append(str(f'>>>> {title}论文生成成功，文件路径：{path}\n'))
        self.ui.request1.setText(str(f''))
        self.ui.request2.setText(str(f''))
        self.ui.request3.setText(str(f''))
        # self.ui.ask1.setText(str(f''))
        # self.ui.ask2.setText(str(f''))
        # self.ui.ask3.setText(str(f''))
        self.ui.comboBox.setCurrentIndex(0)
        self.ui.comboBox_2.setCurrentIndex(0)
        self.ui.comboBox_3.setCurrentIndex(0)

    # 更新分数
    def updateScore(self):
        studentName = self.message[self.index]['studentName']
        title = self.message[self.index]['title']
        defenseScore = self.message[self.index]['defenseScore']
        thesisScore = self.message[self.index]['thesisScore']
        number = self.message[self.index]['number']
        record = {
            'studentName': studentName,
            'title': title,
            'defenseScore': defenseScore,
            'thesisScore':thesisScore,
            'number': number,
        }
        result = getCurrentTime(self.index).split('~')
        path = Word.updateScore(record , result[0] , result[1])
        self.ui.logText.append(str(f'>>>> {title}论文分数录入成功，文件路径：{path}\n'))
        QMessageBox.warning(None, "文档调整成功", "文档调整成功")

    # 时间调整
    # def timeAdjustment(self):
    #    record = {
    #        'studentName': self.message[self.index]['studentName'],
    #        'title': self.message[self.index]['title']
    #    }
    #    result = getCurrentTime(self.index).split('~')
    #    Word.timeAdjustment(record , result[0] , result[1])
    #    QMessageBox.warning(None, "时间调整成功", "时间调整成功")

# 获取当前时间
def getCurrentTime(index):
    global afterFirstNo
    # 当前学生上午答辩
    if index < afterFirstNo - 1:
        minStr = ''
        afterMinStr = ''
        currentMin = 0
        currentHour = 8
        flag = False
        for i in range(index + 1):
            if currentMin < 10:
                minStr = f"0{currentMin}"
            else:
                minStr = f"{currentMin}"
            currentMin = currentMin + 5
            if currentMin >= 60:
                flag = True
                currentMin = 0
                currentHour = currentHour + 1
            if currentMin < 10:
                afterMinStr = f"0{currentMin}"
            else:
                afterMinStr = f"{currentMin}"
        if flag:
            return f'{currentHour-1}:{minStr} ~ {currentHour}:{afterMinStr}'
        else:
            return f'{currentHour}:{minStr} ~ {currentHour}:{afterMinStr}'
    # 当前学生为下午答辩
    else:
        minStr = ''
        afterMinStr = ''
        currentMin = 0
        currentHour = 2
        flag = False
        for i in range(index - afterFirstNo + 2):
            if currentMin < 10:
                minStr = f"0{currentMin}"
            else:
                minStr = f"{currentMin}"
            currentMin = currentMin + 5
            if currentMin >= 60:
                flag = True
                currentMin = 0
                currentHour = currentHour + 1
            if currentMin < 10:
                afterMinStr = f"0{currentMin}"
            else:
                afterMinStr = f"{currentMin}"
        if flag:
            return f'{currentHour-1}:{minStr} ~ {currentHour}:{afterMinStr}'
        else:
            return f'{currentHour}:{minStr} ~ {currentHour}:{afterMinStr}'


# 运行二窗口
def runWin2(message):
    global ex
    ex = showWin2(message)

# 运行一窗口
def runWin1():
    global ex
    app = QApplication(sys.argv)
    ex = showWin1()
    app.exec_()

# 主函数执行
def main():
    runWin1()

if __name__ == "__main__":
    main()